import argparse
from ctypes import *
import pmu_config 

def get_cmd():
    parser = argparse.ArgumentParser(description='nanobench suit')
    parser.add_argument('-s', '--show', help='show offered event name', action='store_true') 
    parser.add_argument('-i', '--cpuinfo', help='show cpu info', action='store_true') 
    parser.add_argument('-e', '--event', metavar='', help='set event name, split multiple events with \',\'') 
    parser.add_argument('-l', '--loop', metavar='', help='set loop') 
    parser.add_argument('-u', '--unroll', metavar='', help='set unroll') 
    parser.add_argument('-c', '--cpu', metavar='', help='set cpu', default=-1, type=int) 
    parser.add_argument('--base_freq', metavar='', help='get cpu base frequency') 
    parser.add_argument('--run_freq', metavar='', help='get cpu run frequency') 
    return parser.parse_args()

def show_pmu_name_list(pmu_data):
    print('offerd pmu event:')
    for name, value in pmu_data.items():
        print('    %s %x' % (name, value))
    with open('pmu_events', 'w') as f:
        f.write('%d\n' % len(pmu_data))
        for name, value in pmu_data.items():
            f.write('%s %x\n' % (name, value))

def get_cpu_info():
    cpu_info = cdll.LoadLibrary("./libcpuinfo.so")
    cpu_info.get_cpu_info()

def start_test(args, pmu_data):
    if not args.event:
        args.event = 'cycles,instructions'
    print(args)
    events = args.event.split(',')
    c_events = (c_uint64 * len(events))()
    for i, e in enumerate(events):
        if e not in pmu_data.keys():
            print('event \'' + e + '\' not support')
            return
        c_events[i] = pmu_data[e]
        print('add %#x' % pmu_data[e])
    start = cdll.LoadLibrary("./libnanobench.so")
    start.start(args.cpu, args.loop, args.event, c_events, len(c_events))


if __name__ == "__main__":
    pmu_data = pmu_config.PmuConfig.get_pmu_data_by_json('pmu.json')
    args = get_cmd()
    if args.show:
        show_pmu_name_list(pmu_data)
    elif args.cpuinfo:
        get_cpu_info()
    else:
        start_test(args, pmu_data)
    


